package org.mfoyou.agent.center.service;

import org.mfoyou.agent.center.dao.inf.*;
import org.mfoyou.agent.common.dao.domain.*;
import org.mfoyou.agent.common.dao.domain.HuawuWorkerExample.Criteria;
import org.mfoyou.agent.common.inf.IAccount;
import org.mfoyou.agent.utils.common.StringUtils;
import org.mfoyou.agent.utils.sql.MybatisGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 用户账户service
 *
 * @author hzhang7
 */
@Service
public class AccountService implements IAccount {

    private static final Logger logger = LoggerFactory.getLogger(AccountService.class);

    @Autowired
    HuawuUserMapper huawuUserMapper;

    @Autowired
    HuawuAgentInfoMapper huawuAgentInfoMapper;

    @Autowired
    HuawuAgentWxInfoMapper huawuAgentWxInfoMapper;

    @Autowired
    HuawuThirdUserMapper huawuThirdUserMapper;

    @Autowired
    HuawuWorkerMapper huawuWorkerMapper;

    @Autowired
    HuawuIdcardInfoMapper huawuIdcardInfoMapper;

    @Autowired
    HuawuSystemMapper HuawuSystemMapper;

    @Autowired
    HuawuServiceCouponRuleMapper huawuServiceCouponRuleMapper;

    @Autowired
    HuawuServiceCouponMapper huawuServiceCouponMapper;

    @Autowired
    HuawuServiceUserCouponMapper huawuServiceUserCouponMapper;

    @Override
    public HuawuUser login(String phone, String makePassWord, Integer agentId) {
        HuawuUserExample huawuUserExample = new HuawuUserExample();
        huawuUserExample.or().andUserPhoneEqualTo(phone).andUserPasswordEqualTo(makePassWord).andAgentIdEqualTo(agentId);
        List<HuawuUser> list = huawuUserMapper.selectByExample(huawuUserExample);
        if (list.size() == 1) {
            list.get(0).setUserPassword(null);
            return list.get(0);
        }
        return null;
    }

    @Override
    public HuawuAgentInfo getAgentInfoByAgentId(Integer userId) {
        return huawuAgentInfoMapper.selectByPrimaryKey(userId);
    }

    @Override
    public HuawuAgentWxInfo getAgentWxInfo(Integer agentId, Integer appId) {
        HuawuAgentWxInfoExample huawuAgentWxInfoExample = new HuawuAgentWxInfoExample();
        huawuAgentWxInfoExample.or().andAgentIdEqualTo(agentId).andXcxTypeEqualTo(appId);
        List<HuawuAgentWxInfo> list = huawuAgentWxInfoMapper.selectByExample(huawuAgentWxInfoExample);
        return list == null || list.size() != 1 ? null : list.get(0);
    }

    @Override
    public HuawuThirdUser getThirdUser(Integer agentId, Integer appId, String openId) {
        HuawuThirdUserExample huawuThirdUserExample = new HuawuThirdUserExample();
        huawuThirdUserExample.or().andAgentIdEqualTo(agentId).andAppTypeIdEqualTo(appId).andOpenIdEqualTo(openId);
        List<HuawuThirdUser> list = huawuThirdUserMapper.selectByExample(huawuThirdUserExample);
        return list == null || list.size() == 0 ? null : list.get(0);
    }

    /**
     * 根据userId找user
     */
    @Override
    public HuawuUser getUserInfoByUserId(Integer userId) {
        HuawuUser selectByPrimaryKey = huawuUserMapper.selectByPrimaryKey(userId);
        selectByPrimaryKey.setUserPassword(null);
        HuawuIdcardInfo selectByPrimaryKey2 = huawuIdcardInfoMapper.selectByPrimaryKey(selectByPrimaryKey.getUserId());
        if (selectByPrimaryKey2 != null) {
            selectByPrimaryKey.setUserName(selectByPrimaryKey2.getUserTrueName());
        }
        return selectByPrimaryKey;
    }

    /**
     * 根据电话找user
     */
    @Override
    public HuawuUser getUserInfoByPhone(String phone, Integer agentId) {
        HuawuUserExample huawuUserExample = new HuawuUserExample();
        huawuUserExample.or().andUserPhoneEqualTo(phone).andAgentIdEqualTo(agentId);
        List<HuawuUser> selectByExample = huawuUserMapper.selectByExample(huawuUserExample);
        if (selectByExample == null || selectByExample.size() == 0) {
            return null;
        }
        return selectByExample.get(0);
    }

    /**
     * 根据电话找user
     */
    @Override
    public HuawuUser getUserInfoByPhoneV2(String phone, Integer agentId) {
        HuawuUserExample huawuUserExample = new HuawuUserExample();
        huawuUserExample.or().andUserPhoneEqualTo(phone).andAgentIdIn(Arrays.asList(agentId, -2));
        huawuUserExample.setOrderByClause(" agent_id asc");
        List<HuawuUser> selectByExample = huawuUserMapper.selectByExample(huawuUserExample);
        if (selectByExample == null || selectByExample.size() == 0) {
            return null;
        }
        return selectByExample.get(0);
    }

    /**
     * 注册用户
     *
     * @param huawuUser
     * @return
     */
    @Override
    public HuawuUser registUser(HuawuUser huawuUser) {

        if (huawuUser.getUserNickName() != null) {
            huawuUser.setUserNickName(StringUtils.filterEmoji(huawuUser.getUserNickName()));
        }

        huawuUserMapper.insertSelective(huawuUser);
        if (huawuUser.getUserId() != null) {
            // 当前用户是通过分享的二维码进入的那么将为当前用户和分享者随机生成优惠券
            if (huawuUser.getSource() != null && huawuUser.getSource() > 0) {
                generateShareCoupon(huawuUser);
            }
            return huawuUserMapper.selectByPrimaryKey(huawuUser.getUserId());
        }
        return null;
    }

    @Override
    public Integer registAgent(HuawuUser huawuUser) {
        String sql = "select min(user_id) user_id from huawu_user where user_id >3000";
        Integer userid = Integer.parseInt(HuawuSystemMapper.select_item(sql).get("user_id").toString()) - 1;
        huawuUser.setUserId(userid);
        huawuUserMapper.insertSelectiveV2(huawuUser);
        return huawuUser.getUserId();
    }

    @Override
    public int modifyUser(HuawuUser huawuuserSave) {
        if (huawuuserSave.getUserNickName() != null)
            huawuuserSave.setUserNickName(StringUtils.filterEmoji(huawuuserSave.getUserNickName()));
        return huawuUserMapper.updateByPrimaryKeySelective(huawuuserSave);
    }

    @Override
    public int addThirdUser(HuawuThirdUser huawuThirdUser) {
        return huawuThirdUserMapper.insertSelective(huawuThirdUser);
    }

    @Override
    public HuawuWorker getWorkerInfo(Integer userId) {
        return huawuWorkerMapper.selectByPrimaryKey(userId);
    }

    @Override
    public HuawuIdcardInfo getIdcardInfo(Integer userId) {
        return huawuIdcardInfoMapper.selectByPrimaryKey(userId);
    }

    @Override
    public int updateMfoyouIdcardInfo(HuawuIdcardInfo huawuIdcardInfo) {
        return huawuIdcardInfoMapper.updateByPrimaryKeySelective(huawuIdcardInfo);
    }

    @Override
    public int addIdcardInfo(HuawuIdcardInfo huawuIdcardInfo) {
        return huawuIdcardInfoMapper.insertSelective(huawuIdcardInfo);
    }

    @Override
    public List<HuawuUser> userListById(List<Integer> ids) {
        HuawuUserExample huawuUserExample = new HuawuUserExample();
        huawuUserExample.or().andUserIdIn(ids);
        return huawuUserMapper.selectByExample(huawuUserExample);
    }

    @Override
    public HuawuThirdUser getThirdByUserId(int userId, int appid) {
        HuawuThirdUserExample huawuThirdUserExample = new HuawuThirdUserExample();
        huawuThirdUserExample.or().andUserIdEqualTo(userId).andAppTypeIdEqualTo(appid);
        return MybatisGenerator.getOneValue(huawuThirdUserMapper.selectByExample(huawuThirdUserExample));
    }

    @Override
    public List<HuawuWorker> getAgentMfoyouWorkerList(List<Integer> users, Integer agentId) {
        HuawuWorkerExample huawuWorkerExample = new HuawuWorkerExample();
        Criteria andAgentIdEqualTo = huawuWorkerExample.or().andAgentIdEqualTo(agentId);
        if (users != null) {
            andAgentIdEqualTo.andUserIdIn(users);
        }
        return huawuWorkerMapper.selectByExample(huawuWorkerExample);
    }

    @Override
    public Integer getNewUserAmount(Integer agentId) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        HuawuUserExample huawuUserExample = new HuawuUserExample();
        huawuUserExample.or().andAgentIdEqualTo(agentId).andUserRegistTimeGreaterThanOrEqualTo(calendar.getTime());
        return huawuUserMapper.countByExample(huawuUserExample);
    }

    @Override
    public HuawuUser userByName(String name, int agentId) {
        HuawuUserExample huawuUserExample = new HuawuUserExample();
        huawuUserExample.or().andUserNickNameEqualTo(name).andAgentIdEqualTo(agentId);
        List<HuawuUser> selectByExample = huawuUserMapper.selectByExample(huawuUserExample);
        return selectByExample == null || selectByExample.size() == 0 ? null : selectByExample.get(0);
    }


    @Override
    public Map<String, Object> getThirdInfo(Integer userId) {
        Map<String, Object> ret = new HashMap<>();
        String sql1 = "select wallet_freight_account money from huawu_wallet where user_id = " + userId;
        Map<String, Object> select_item = HuawuSystemMapper.select_item(sql1);
        String sql2 = "select user_id,youzan_store_pic,youzan_store_name,state from huawu_youzan where user_id = " + userId;
        Map<String, Object> select_item2 = HuawuSystemMapper.select_item(sql2);
        if (select_item != null) {
            ret.putAll(select_item);
        }
        if (select_item2 != null) {
            ret.putAll(select_item2);
        }
        return ret;
    }

    /**
     * 为当前用户和分享者用户生成优惠券
     *
     * @param user  用户信息
     */
    private void generateShareCoupon(HuawuUser user) {
        // 从 huawu_service_coupon_rule 表中查询唯一的一条分享规则(规则只有一条)
        HuawuServiceCouponRule rule = huawuServiceCouponRuleMapper.selectRule();

        if (rule != null) {
            // 查询出优惠券规则
            HuawuServiceCouponRule huawuServiceCouponRule = huawuServiceCouponRuleMapper.selectRule();
            // 计算优惠券有效期时间范围
            Date start = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, huawuServiceCouponRule.getMonth() + 1);
            Date end = calendar.getTime();

            // 随机生成新用户优惠券金额和分享者优惠券金额
            Random random = new Random();
            int userCouponNumber = random.nextInt( rule.getReshareEnd() - rule.getReshareStart() + 1) + rule.getReshareStart();
            int shareCouponNumber = random.nextInt( rule.getShareEnd() - rule.getShareStart() + 1) + rule.getShareStart();
            userCouponNumber = userCouponNumber * 100;
            shareCouponNumber = shareCouponNumber * 100;

            // 插入用户优惠券表
            insertShareCoupon(user.getUserId(), user.getAgentId(), "新人优惠券", "全场通用", 1, 1, userCouponNumber, start, end);
            Integer userCouponId = insertShareCoupon(user.getSource(), user.getAgentId(), "推荐优惠券", "全场通用", 1, -1, shareCouponNumber, null, null);
            // 将用户优惠券id存储到用户信息表中的 source_coupon_id 字段以用于在新用户下第一单以后激活推荐者优惠券
            if (userCouponId != null) {
                logger.info(String.format("将用户优惠券id存储到用户信息表中的 source_coupon_id 字段以用于在新用户下第一单以后激活推荐者优惠券: source_coupon_id=[%s]", userCouponId));
                huawuUserMapper.updateSourceCouponIdByPrimaryKey(userCouponId, user.getUserId());
            }
        }
    }

    /**
     * 插入优惠券
     *
     * @param userId        用户id
     * @param agentId       代理商id
     * @param couponName    优惠券名称
     * @param couponText    优惠券详情
     * @param useType       用户类型
     * @param couponState   优惠券状态: -1 未激活; 0 已使用; 1 未使用
     * @param reduceValue   金额
     * @param start         有效期开始时间
     * @param end           有效期结束时间
     */
    private Integer insertShareCoupon(Integer userId, Integer agentId, String couponName, String couponText, Integer useType, Integer couponState,
                                   Integer reduceValue, Date start, Date end) {
        // 由于是分享系统生成的并且每个人的金额是不一样所以设置 totalCount=1 couponSold=1
        HuawuServiceCoupon serviceCoupon = new HuawuServiceCoupon(agentId, couponName, 1, 1, couponText, new Date(),
                new Date(), useType, couponState, reduceValue, start, end);

        huawuServiceCouponMapper.insertSelective(serviceCoupon);
        if (serviceCoupon.getServiceCouponId() != null && serviceCoupon.getServiceCouponId() > 0) {
            // touchState = -1 未激活
            HuawuServiceUserCoupon userCoupon = new HuawuServiceUserCoupon(serviceCoupon.getServiceCouponId(), -1, userId, reduceValue, new Date());
            huawuServiceUserCouponMapper.insertSelective(userCoupon);
            return userCoupon.getTouchId();
        }
        return null;
    }
}
